package com.tvunetworks.center.user.service.impl;

import com.tvunetworks.center.common.model.dto.user.UserFeatureDTO;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.center.user.mapper.UserMapper;
import com.tvunetworks.center.user.mapper.UserRoleMapper;
import com.tvunetworks.center.user.model.UserRole;
import com.tvunetworks.center.user.service.UserRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @program: tvucc-aggregator
 * @description: UserRoleServiceImpl
 * @author lebronchen
 * @create: 2019-06-03 18:14
 **/
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean checkUserRole(String userId, String feature) {
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(feature)) {
            return false;
        }
        UserRole record = new UserRole().setUserId(userId).setFeature(feature);
        List<UserRole> userRoles = userRoleMapper.select(record);
        if (userRoles == null || userRoles.size() == 0) {
            return false;
        }
        return userRoles.get(0).getValue() == 1;
    }

    @Override
    public List<UserFeatureDTO> listUserRole(String userId) {
        return userRoleMapper.listUserRole(userId);
    }

    @Override
    public void updateUserRole(String userId, String feature, Integer enable) {
        UserRole record = new UserRole()
                .setUserId(userId)
                .setFeature(feature);
        List<UserRole> list = userRoleMapper.select(record);
        if (CollectionUtils.isEmpty(list)) {
            record.setValue(enable)
                    .setId(MyUtil.getUUID());
            userRoleMapper.insert(record);
        } else {
            UserRole userRole = list.get(0);
            userRole.setValue(enable);
            userRoleMapper.updateByPrimaryKeySelective(userRole);
        }
    }

    @Override
    public void removeUserSonRole(String userId, String feature) {
        List<String> sonUserIds = userMapper.listSonUserIds(userId);
        if (CollectionUtils.isEmpty(sonUserIds)) {
            return;
        }
        userRoleMapper.removeUserRole(sonUserIds, feature);
    }
}
